<?php

namespace App\Http\Controllers\Home;

use App\Admin\Category;
use App\Admin\Paper;
use App\Admin\Test;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class ExamController extends Controller
{
    public function index(){
	if(Auth::guard('member')->user()->role_id == '3') {
        	return view('home.exam.index');
    	}else{
    		Auth::guard('member')->logout();
            return view('home.index.login');
        }
    }
    public function exam(Request $request){
        if ($request -> method() === 'GET'){
            $data = Paper::where('isdel','2') -> get();
            foreach($data as $K=>$v){
                $v -> category_name = $v -> category -> category_name;
            }
            $data = $data -> toArray();
            $res = [
                'data' => $data,
                'categories' => Category::where('isdel','2') -> pluck('category_name') -> toArray()
            ];
            $res = json_encode($res);
            return view('home.exam.exam',compact('res'));
        }else{
            $user_id = Auth::guard('member') -> user() -> id;
            $data = $request -> all();
            $data['member_id'] = $user_id;
            $data['addtime'] = date('Y-m-d H:i:s');
            if (Test::create($data)){
                return 1;
            }else{
                return 0;
            }
        }
    }

    public function lishi(){
        $id = Auth::guard('member')->user() -> id ;
        $data = \App\Home\Test::where('member_id',$id) -> get() -> toArray();
        return view('home.exam.lishi',compact('data'));
    }

    public function test(){
        $id = Auth::guard('member')->user() -> id ;
        $data = \App\Home\Test::where('member_id',$id) -> get() -> toArray();
        $errs = '';
        foreach ($data as $key => $value) {
            $errs .= $value['error_ids'] . ',';
        }
        $errs = rtrim($errs,',');
        $errs = explode(',',$errs);
        $errs = array_unique($errs);
        $questions = [];
        foreach ($errs as $err) {
            $questions[] = Paper::where('id',$err) -> get() -> toArray()[0];
        }
        $data = $questions;
        return view('home.exam.test',compact('data'));
    }
}
